<?php
/**
 * Junction_SqlGenerator
 * 
 * Static class which builds SQL queries given a
 * Junction_Class instance.
 * 
 * @author Patrick J. Mizer <patrick.mizer@gmail.com>
 */
using("Junction_Class");
using("Junction_Table");
using("Junction_Column");

class Junction_SqlGenerator
{
	/**
	 * Generates a SELECT statement.
	 * 
	 * @param Junction_Class
	 * @param Junction_Criterion
	 * @return string
	 */
	public static function generateSelect(Junction_Class $class, Junction_Criterion $criterion = null)
	{
		$sql = 'SELECT ';
		
		$attributes = $class->getAttributes();
		$numAttributes = count($attributes);
		$i = 0;
		foreach($attributes as $attribute){
			$sql .= Junction_SqlGenerator::prepareSqlPredicate($attribute);
			
			$sql .= (++$i < $numAttributes ? ', ' : ' ');
		}	
		
		$sql .= ' FROM '; 
		
		$tables = $class->getTables();
		$numTables = count($tables);
		$i = 0;
		foreach($tables as $table){
			$sql .= Junction_SqlGenerator::addTicks($table->getName());
			$sql .= (++$i < $numTables ? ', ' : ' ');
		}
		
		
		if($criterion != null){
			$sql .= ' WHERE ';
			
			$sql .= Junction_SqlGenerator::prepareSqlPredicate($criterion->getLeftHandOperand());
			$sql .= ' ' . $criterion->getOperator() . ' ' 
				. Junction_SqlGenerator::prepareSqlPredicate($criterion->getRightHandOperand());
		}
		return $sql;
	}
	
	/**
	 * Convenience method for building `table`.`column` strings
	 * 
	 * @param Junction_Column
	 * @return string
	 */
	private static function prepareSqlPredicate($predicate)
	{
		if($predicate instanceof Junction_Column){
			return Junction_SqlGenerator::addTicks($predicate->getTable()->getName()).
				'.'.Junction_SqlGenerator::addTicks($predicate->getName());
		}
		
		return Junction_SqlGenerator::addQuotes($predicate);
	}
	
	/**
	 * Conveneince method for adding ticks around a string
	 * 
	 * @param string
	 * @return string
	 */
	private static function addTicks($str)
	{
		return '`'.$str.'`';
	}
	
	/**
	 * Conveneince method for adding quotes around a string
	 * 
	 * @param string
	 * @return string
	 */	
	private static function addQuotes($str)
	{
		return "'".addslashes($str)."'";
	}
}
?>
